package com.liukaixin.product.ru.service;

import com.alibaba.fastjson.JSON;
import com.liukaixin.product.ru.AppController;
import com.liukaixin.product.ru.data.model.User;
import com.orhanobut.logger.Logger;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by liukaixin on 16/8/31.
 */

public class ServiceFactory {

    private final static String IP = "123.57.227.14";

    private final static String PORT = "8888";

    public final static String BASE_URL = "http://" + IP + ":" + PORT + "/" +
            "racing-union-0.1.3/" +"racing-union/";

//    private final static String IP = "10.20.55.214";
//
//    private final static String PORT = "8080";
//
//    public final static String BASE_URL = "http://" + IP + ":" + PORT + "/"
//            + "racing-union/";

    private static String TOKEN = "";

    private static OkHttpClient httpClient = null;


    public static <T> T createRetrofitService(final Class<T> clazz, final String baseUrl) {

        User user = JSON.parseObject(AppController.getInstance().getCache().getAsString("user"),
                User.class);
        if (user != null) {
            TOKEN = user.getToken();
        }

        if (httpClient == null) {
            httpClient = new OkHttpClient.Builder().addInterceptor(chain -> {
                Request original = chain.request();

                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder()
                        .header("Authorization", TOKEN)
                        .method(original.method(), original.body());

                Request request = requestBuilder.build();
                return chain.proceed(request);
            }).build();
        }

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient)
                .build();

        return retrofit.create(clazz);
    }
}
